package com.java.business.system.database.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.java.business.system.common.dao.CommonMapper;
import com.java.business.system.database.dao.FixBaseMapper;
import com.java.core.bean.LowerCaseKeyMap;
import com.java.core.utils.IdUtils;
import com.java.core.utils.RequestUtils;
import com.java.core.utils.SessionUtils;

@Transactional
@Service
public class FixBaseService {

	@Autowired
	private FixBaseMapper mapper;

	@Autowired
	private JdbcTemplate jdbc;

	@Autowired
	private CommonMapper commonMapper;

	public List<LowerCaseKeyMap> getTableColumns(String tablename) {
		return mapper.getTableColumns(tablename);
	}

	/**
	 * 同步业务数据
	 * 
	 * @return
	 * @throws RuntimeException
	 */
	public int syncBuis() throws RuntimeException {
		//删除多余的数据
		jdbc.update("UPDATE ELE_BUDGET_SYNCDATA SET DELETED = 1 WHERE (B_VOU_ID, COPYID) IN (SELECT B_VOU_ID, B_VOU_ID FROM ELE_BUDGET_SYNCDATA WHERE DELETED = 0 AND COPYID IS NULL MINUS SELECT B_VOU_ID, B_VOU_ID FROM V_ELE_BUDGET_SYNCDATA)");
		//修改调减数据
		jdbc.update("UPDATE ELE_BUDGET_SYNCDATA A SET MINUS_MONEY = (SELECT MINUS_MONEY FROM V_ELE_BUDGET_SYNCDATA B WHERE A.B_VOU_ID = B.B_VOU_ID) WHERE A.DELETED = 0 AND A.B_VOU_ID IN (SELECT B_VOU_ID FROM (SELECT B_VOU_ID, MINUS_MONEY FROM V_ELE_BUDGET_SYNCDATA MINUS SELECT B_VOU_ID, MINUS_MONEY FROM ELE_BUDGET_SYNCDATA))");
		return jdbc
				.update("insert into ele_budget_syncdata\n"
						+ "  select *\n"
						+ "    from v_ele_budget_syncdata\n"
						+ "   where b_vou_id in (select b_vou_id\n"
						+ "                        from v_ele_budget_syncdata\n"
						+ "                      minus\n"
						+ "                      select b_vou_id from ele_budget_syncdata)");
	}

	/**
	 * 修改业务数据
	 * 
	 * @param request
	 */
	public void updateBuis(HttpServletRequest request) {
		Map<String, String> params = RequestUtils.getParams(request);
		String b_vou_id = params.get("b_vou_id");
		Map<String, String> p = new HashMap<String, String>();
		p.put("sql", "select * from ele_budget_syncdata where b_vou_id='"
				+ b_vou_id + "'");
		LowerCaseKeyMap map = commonMapper.queryForMap(p);
		if (map == null) {
			throw new RuntimeException("操作失败！");
		}
		p.put("sql",
				"select lower(column_name) column_name from user_tab_columns where table_name=upper('ele_budget_syncdata')");
		List<LowerCaseKeyMap> columns = commonMapper.queryBySql(p);
		String ip = RequestUtils.getIp(request);
		String userid = SessionUtils.getSessionUserId(request);
		String cont = "业务数据修改记录-"+b_vou_id+"：";
		int len = cont.length();
		for (LowerCaseKeyMap keys : columns) {
			String key = (String) keys.get("column_name");
			if (params.keySet().contains(key)
					&& !params.get(key).equals(String.valueOf(map.get(key)))) {
				if (cont.length() > 0) {
					cont += "\n";
				}
				cont += "字段:" + key + "(修改前：" + map.get(key) + "，修改后："
						+ params.get(key) + ")";
			}
		}
		if (cont.length() == len) {
			return;
		}
		params.put("id", IdUtils.uuid());
		params.put("ip", ip);
		params.put("userid", userid);
		params.put("cont", cont);
		mapper.updateBuis(params);
	}

	/**
	 * 拆分业务数据
	 * 
	 * @param request
	 */
	public void chaifenBuis(HttpServletRequest request) {
		Map<String, String> params = RequestUtils.getParams(request);
		String copyid = params.get("copyid");
		Map<String, String> p = new HashMap<String, String>();
		p.put("sql", "select * from ele_budget_syncdata where b_vou_id='"
				+ copyid + "'");
		LowerCaseKeyMap map = commonMapper.queryForMap(p);
		if (map == null) {
			throw new RuntimeException("操作失败！");
		}
		// 设置ID
		params.put("b_vou_id", IdUtils.uuid());
		// 设置不能更改的值
		params.put("budgettype_code",
				getStringValue(map.get("budgettype_code")));
		params.put("type_id", getStringValue(map.get("type_id")));
		params.put("adjust_way", getStringValue(map.get("adjust_way")));
		params.put("is_valid", getStringValue(map.get("is_valid")));
		params.put("is_end", getStringValue(map.get("is_end")));
		params.put("budget_groupid", getStringValue(map.get("budget_groupid")));
		params.put("ba_code", getStringValue(map.get("ba_code")));
		params.put("ba_name", getStringValue(map.get("ba_name")));
		params.put("toctrlid", getStringValue(map.get("toctrlid")));
		params.put("fromctrlid", getStringValue(map.get("fromctrlid")));

		String ip = RequestUtils.getIp(request);
		String userid = SessionUtils.getSessionUserId(request);
		String cont = "业务数据拆分记录，拆分编号：" + copyid + "，拆分生成的编号："
				+ params.get("b_vou_id");
		params.put("id", IdUtils.uuid());
		params.put("ip", ip);
		params.put("userid", userid);
		params.put("cont", cont);
		mapper.chaifenBuis(params);
	}

	/**
	 * 删除业务数据
	 * 
	 * @param request
	 */
	public void deleteBuis(HttpServletRequest request) {
		Map<String, String> params = RequestUtils.getParams(request);
		// 记录日志
		String ip = RequestUtils.getIp(request);
		String userid = SessionUtils.getSessionUserId(request);
		String cont = "业务数据删除记录，删除编号：" + params.get("b_vou_id");
		params.put("id", IdUtils.uuid());
		params.put("ip", ip);
		params.put("userid", userid);
		params.put("cont", cont);
		mapper.deleteBuis(params);
	}

	private String getStringValue(Object value) {
		if (value == null) {
			return "";
		}
		return String.valueOf(value);
	}
}
